<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('借阅人')" prop="borrower">
            <UserSelect v-model="form.borrower" :placeholder="$t('借阅人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applicationTime">
            <DatePicker
              v-model="form.applicationTime"
              :placeholder="$t('申请时间')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('截止时间')" prop="deadlineTime">
            <DatePicker
              v-model="form.deadlineTime"
              type="date"
              :disabled="form.actStatus === 'W'"
              :placeholder="$t('截止时间')"
              :pick-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('允许下载')" prop="downloadSwitch">
            <el-switch v-model="form.downloadSwitch" :disabled="form.actStatus === 'W'" active-color="#13ce66" inactive-color="#ff4949" :active-value="'Y'" :inactive-value="'N'" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('借阅说明')" prop="borrowingInstructions">
            <el-input v-model="form.borrowingInstructions" type="textarea" :placeholder="$t('借阅说明')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header" style="margin-top: 10px">
        <span class="area-header-title">{{ $t('文件列表') }}</span>
      </div>
      <el-table :data="form.fileBorrowingList" border>
        <el-table-column :label="$t('附件类型')" prop="type" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fileBorrowingList.' + scope.$index + '.type'">
              {{ scope.row.type }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('业务名称')" prop="businessName" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fileBorrowingList.' + scope.$index + '.businessName'">
              {{ scope.row.businessName }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件名称')" prop="name" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fileBorrowingList.' + scope.$index + '.name'">
              <el-button
                v-show="scope.row.status === '借阅中' && form.actStatus === 'W'"
                type="text"
                @click="onlinePreview(scope.row.fileId)"
              >{{ scope.row.name }}</el-button>
              <span v-show="!(scope.row.status === '借阅中' && form.actStatus === 'W')">
                {{ scope.row.name }}
              </span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('状态')" prop="status" align="center" width="100">
          <template slot-scope="scope">
            <el-form-item :prop="'fileBorrowingList.' + scope.$index + '.status'">
              <span v-show="scope.row.status === '借阅中'" style="color:#13ce66;">
                {{ $t(scope.row.status) }}
              </span>
              <span v-show="scope.row.status === '已过期'" style="color:red;">
                {{ $t(scope.row.status) }}
              </span>
              <span v-show="scope.row.status !== '借阅中' && scope.row.status !== '已过期'" style="color:orange;">
                {{ $t(scope.row.status) }}
              </span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="form.downloadSwitch === 'Y' && form.actStatus === 'W' && new Date().getTime() < new Date(form.deadlineTime).getTime()" :label="$t('下载')" prop="" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-download" @click="downloadFile(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" prop="" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="openHandle">{{ $t('添加') }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:oaFileLending" :btn-hide="btnHide" :menu-key="menuKey" />
    </div>

    <!-- 添加或修改文档借阅对话框 -->
    <el-dialog
      :title="$t('借阅列表')"
      :visible.sync="listOfBorrowedFilesOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <listOfBorrowedFiles ref="listOfBorrowedFiles" />
    </el-dialog>
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import { saveOaFileLending, getOaFileLending, oaFileBorrowingDelete } from '@/api/oa/oaFileLending/oaFileLending'
import listOfBorrowedFiles from './listOfBorrowedFiles.vue'
import { downLoadFileOpen } from '@/utils/zipdownload'

export default {
  components: {
    listOfBorrowedFiles
  },
  data() {
    return {
      // 菜单标识
      menuKey: 'oa_file_lending',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now()
        },
        shortcuts: [{
          text: '三  天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', date)
          }
        }, {
          text: '七  天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: '十  天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 10)
            picker.$emit('pick', date)
          }
        }, {
          text: '二十天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 20)
            picker.$emit('pick', date)
          }
        }, {
          text: '三十天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }]
      },
      // 是否隐藏保存按钮
      btnHide: false,
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        borrower: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        applicationTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        deadlineTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        borrowingInstructions: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      fileBorrowingListRules: {},
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      listOfBorrowedFilesOpen: false
    }
  },
  created() {
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      console.log('新增文档借阅')
      if (data != null && data.id !== undefined) {
        getOaFileLending(data.id).then(response => {
          this.form = response.data
          this.calculateReviewStatus(response.data.fileBorrowingList)
          this.loading = false
        })
      } else {
        this.loading = false
        this.reset()
      }
    },
    // 计算审阅状态
    calculateReviewStatus(rows) {
      rows.forEach(item => {
        console.log(item)
        if (new Date(this.form.deadlineTime).getTime() > new Date().getTime()) {
          if (this.form.actStatus === 'W') {
            item.status = '借阅中'
          } else {
            item.status = '待审核'
          }
        } else {
          item.status = '已过期'
        }
      })
    },
    // 预览附件
    onlinePreview(id) {
      this.$refs.OnlinePreview.onlinePreviewFile(id)
    },
    // 打开借阅列表
    openHandle() {
      this.listOfBorrowedFilesOpen = true
      this.$nextTick(() => {
        this.$refs.listOfBorrowedFiles.enterpriseMethod(null)
      })
    },
    // 添加明细
    addHandle(rows) {
      if (rows !== null && rows !== undefined) {
        rows.forEach(item => {
          const row = {
            fileId: item.id,
            type: item.type,
            name: item.name,
            businessName: item.businessName,
            status: '未生效'
          }
          if (!(this.form.fileBorrowingList instanceof Array)) {
            this.$set(this.form, 'fileBorrowingList', [])
          }
          this.$nextTick(() => {
            this.form.fileBorrowingList.push(row)
          })
        })
      }
    },
    // 删除
    delHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return oaFileBorrowingDelete(id)
          }).then(() => {
          this.form.fileBorrowingList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {
          })
      } else {
        this.form.fileBorrowingList.splice(index, 1)
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        borrower: this.$store.state.user.userId,
        applicationTime: new Date(),
        deadlineTime: undefined,
        downloadSwitch: 'Y',
        borrowingInstructions: undefined,
        remark: undefined,
        actTitle: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        fileBorrowingList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function(type) {
      this.$refs['form'].validate(valid => {
        // 验证数据
        if (valid) {
          // 弹出遮罩层
          this.loading = true
          // 保存数据
          saveOaFileLending(this.form).then(response => {
            if (response.code === 200) {
              // 点击的按钮是保存并启动流程
              if (type === 'process') {
                // 启动流程
                this.startProcess(response.data.id)
                // 点击的仅保存
              } else {
                this.msgSuccess(this.$t('保存成功'))
                // 关闭form页面
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
              this.loading = false
            }
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.actTitle
      // 业务表名
      processData.dataTable = 'oa_file_lending'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/oaFileLending/oaFileLendingForm'
      processData.viewPath = '@/views/oa/oaFileLending/oaFileLendingView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    downloadFile(row) {
      downLoadFileOpen('/file/fileBase/common/download?id=' + row.fileId)
    }
  }
}
</script>
